// 飞翔小鸟游戏类
class FlappyGame {
    constructor() {
        this.canvas = document.getElementById('flappy-canvas');
        this.ctx = this.canvas.getContext('2d');
        
        this.bird = {
            x: 80,
            y: 200,
            width: 30,
            height: 30,
            velocity: 0,
            gravity: 0.5,
            jumpPower: -8
        };
        
        this.pipes = [];
        this.pipeWidth = 60;
        this.pipeGap = 150;
        this.pipeSpeed = 2;
        
        this.score = 0;
        this.isGameRunning = false;
        this.gameLoop = null;
        
        this.bindEvents();
        this.loadAndDisplayGameData();
    }

    // 初始化游戏
    initGame() {
        this.bird.y = 200;
        this.bird.velocity = 0;
        this.pipes = [];
        this.score = 0;
        this.updateScore();
        
        // 生成初始管道
        for (let i = 0; i < 3; i++) {
            this.generatePipe(this.canvas.width + i * 200);
        }
    }

    // 开始游戏
    async startGame() {
        this.initGame();
        this.isGameRunning = true;
        await this.updateGameStats();
        this.gameLoop = setInterval(() => this.update(), 1000 / 60); // 60 FPS
        this.draw();
    }

    // 停止游戏
    stopGame() {
        this.isGameRunning = false;
        if (this.gameLoop) {
            clearInterval(this.gameLoop);
            this.gameLoop = null;
        }
    }

    // 小鸟跳跃
    jump() {
        if (this.isGameRunning) {
            this.bird.velocity = this.bird.jumpPower;
        }
    }

    // 游戏更新
    update() {
        if (!this.isGameRunning) return;

        // 更新小鸟
        this.bird.velocity += this.bird.gravity;
        this.bird.y += this.bird.velocity;

        // 检查小鸟是否撞到地面或天花板
        if (this.bird.y + this.bird.height > this.canvas.height || this.bird.y < 0) {
            this.gameOver();
            return;
        }

        // 更新管道
        this.pipes.forEach(pipe => {
            pipe.x -= this.pipeSpeed;
        });

        // 移除离开屏幕的管道
        this.pipes = this.pipes.filter(pipe => pipe.x + this.pipeWidth > 0);

        // 生成新管道
        if (this.pipes.length < 3) {
            const lastPipe = this.pipes[this.pipes.length - 1];
            this.generatePipe(lastPipe.x + 200);
        }

        // 检查碰撞和得分
        this.pipes.forEach(pipe => {
            // 检查得分
            if (!pipe.scored && pipe.x + this.pipeWidth < this.bird.x) {
                pipe.scored = true;
                this.score++;
                this.updateScore();
            }

            // 检查碰撞
            if (this.checkCollision(pipe)) {
                this.gameOver();
            }
        });

        this.draw();
    }

    // 生成管道
    generatePipe(x) {
        const minHeight = 50;
        const maxHeight = this.canvas.height - this.pipeGap - minHeight;
        const topHeight = Math.random() * (maxHeight - minHeight) + minHeight;
        
        this.pipes.push({
            x: x,
            topHeight: topHeight,
            bottomY: topHeight + this.pipeGap,
            scored: false
        });
    }

    // 检查碰撞
    checkCollision(pipe) {
        const birdLeft = this.bird.x;
        const birdRight = this.bird.x + this.bird.width;
        const birdTop = this.bird.y;
        const birdBottom = this.bird.y + this.bird.height;
        
        const pipeLeft = pipe.x;
        const pipeRight = pipe.x + this.pipeWidth;
        
        // 检查是否在管道的水平范围内
        if (birdRight > pipeLeft && birdLeft < pipeRight) {
            // 检查是否撞到上管道或下管道
            if (birdTop < pipe.topHeight || birdBottom > pipe.bottomY) {
                return true;
            }
        }
        
        return false;
    }

    // 绘制游戏
    draw() {
        // 清空画布 - 天空背景
        const gradient = this.ctx.createLinearGradient(0, 0, 0, this.canvas.height);
        gradient.addColorStop(0, '#87CEEB');
        gradient.addColorStop(1, '#98D8E8');
        this.ctx.fillStyle = gradient;
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);

        // 绘制管道
        this.pipes.forEach(pipe => {
            this.ctx.fillStyle = '#2ECC71';
            
            // 上管道
            this.ctx.fillRect(pipe.x, 0, this.pipeWidth, pipe.topHeight);
            
            // 下管道
            this.ctx.fillRect(pipe.x, pipe.bottomY, this.pipeWidth, 
                            this.canvas.height - pipe.bottomY);
            
            // 管道边框
            this.ctx.strokeStyle = '#27AE60';
            this.ctx.lineWidth = 2;
            this.ctx.strokeRect(pipe.x, 0, this.pipeWidth, pipe.topHeight);
            this.ctx.strokeRect(pipe.x, pipe.bottomY, this.pipeWidth, 
                              this.canvas.height - pipe.bottomY);
        });

        // 绘制小鸟
        this.ctx.fillStyle = '#F39C12';
        this.ctx.beginPath();
        this.ctx.arc(
            this.bird.x + this.bird.width / 2,
            this.bird.y + this.bird.height / 2,
            this.bird.width / 2,
            0,
            Math.PI * 2
        );
        this.ctx.fill();
        
        // 小鸟眼睛
        this.ctx.fillStyle = '#000';
        this.ctx.beginPath();
        this.ctx.arc(
            this.bird.x + this.bird.width / 2 + 5,
            this.bird.y + this.bird.height / 2 - 5,
            3,
            0,
            Math.PI * 2
        );
        this.ctx.fill();
    }

    // 游戏结束
    async gameOver() {
        this.stopGame();
        await this.saveGameData();
        const data = await this.loadGameData();
        alert(`游戏结束！\n得分: ${this.score}\n最高分: ${data.highScore}`);
    }

    // 更新分数显示
    updateScore() {
        document.getElementById('flappy-score').textContent = this.score;
    }

    // 绑定事件
    bindEvents() {
        // 键盘事件
        document.addEventListener('keydown', (e) => {
            if (e.code === 'Space') {
                e.preventDefault();
                this.jump();
            }
        });

        // 鼠标点击事件
        this.canvas.addEventListener('click', () => {
            this.jump();
        });
    }

    // 保存游戏数据
    async saveGameData() {
        const currentData = await this.loadGameData();
        const gameData = {
            highScore: Math.max(this.score, currentData.highScore || 0),
            lastScore: this.score,
            gamesPlayed: (currentData.gamesPlayed || 0) + 1
        };
        await authManager.saveGameData('flappy', gameData);
    }

    // 加载游戏数据
    async loadGameData() {
        return await authManager.loadGameData('flappy') || { highScore: 0 };
    }

    // 更新游戏统计显示
    async updateGameStats() {
        const data = await this.loadGameData();
        document.getElementById('flappy-high-score').textContent = data.highScore || 0;
    }

    // 加载并显示游戏数据
    async loadAndDisplayGameData() {
        await this.updateGameStats();
    }
}

// 创建游戏实例
let flappyGame;